//--------------------------------------------------------------------------------------------------------------
// <copyright file="ResourceFile.cs" company="Microsoft Corporation" author="David Martos" date="01/01/2007">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Win32;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CSP.Core
{
    /// <summary>
    /// This class allows components to access the translations of their literals.
    /// </summary>
    public class ResourceFile
    {

        private XmlDocument resourceFile;

        /// <summary>
        /// Class constructor. The component searches for a resource file on the resources folder using the default language
        /// found on the registry.
        /// </summary>
        public ResourceFile()
        {
            Errors.InitializeLog();

            try
            {
                //Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles).ToString () + "/Microsoft Shared/web server extensions/12/Resources/csp.es-ES.resx";        
                //string _resourceFilesFolder = RegistryAccess.GetStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, Constants.RegPropInstallationFolder);
                string _resourceFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles).ToString() + Constants.ResourcesFolderSharepoint;

               //string language = RegistryAccess.GetStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, Constants.RegPropDefaultLanguage);

               string language = SPContext.Current.Web.Locale.Name;
               //TODO: HttpContext.Current.Session.LCID;
                string resourcesFileName = string.Empty;

                if (System.Web.HttpContext.Current != null)
                {
                    if (System.Web.HttpContext.Current.Application[Constants.ResourceFile] != null)
                        this.resourceFile = (XmlDocument)System.Web.HttpContext.Current.Application[Constants.ResourceFile];
                    else
                    {                        
                        this.resourceFile = LoadResourceFile(string.Format(Constants.ResourceFileMask, _resourceFilesFolder, language));
                      

                        System.Web.HttpContext.Current.Application[Constants.ResourceFile] = this.resourceFile;
                    }
                }
                else
                    this.resourceFile = LoadResourceFile(string.Format(Constants.ResourceFileMask, _resourceFilesFolder, language));                              
            }
            catch (Exception exception)
            {
                //log.Error(new LogMessage(LogMessageType.CoreResourcesGenericError, exception.Message), exception);
                throw exception;
            }
        }

        public ResourceFile(string language)
        {
            Errors.InitializeLog();

            try
            {
                //Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles).ToString () + "/Microsoft Shared/web server extensions/12/Resources/csp.es-ES.resx";        
                //string _resourceFilesFolder = RegistryAccess.GetStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, Constants.RegPropInstallationFolder);
                string _resourceFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles).ToString() + Constants.ResourcesFolderSharepoint;

                //string language = RegistryAccess.GetStringProperty(Registry.LocalMachine, Constants.CspRegistryKey, Constants.RegPropDefaultLanguage);

                //TODO: HttpContext.Current.Session.LCID;
                string resourcesFileName = string.Empty;

                if (System.Web.HttpContext.Current != null)
                {
                    if (System.Web.HttpContext.Current.Application[Constants.ResourceFile] != null)
                        this.resourceFile = (XmlDocument)System.Web.HttpContext.Current.Application[Constants.ResourceFile];
                    else
                    {
                        this.resourceFile = LoadResourceFile(string.Format(Constants.ResourceFileMask, _resourceFilesFolder, language));


                        System.Web.HttpContext.Current.Application[Constants.ResourceFile] = this.resourceFile;
                    }
                }
                else
                    this.resourceFile = LoadResourceFile(string.Format(Constants.ResourceFileMask, _resourceFilesFolder, language));
            }
            catch (Exception exception)
            {
                //log.Error(new LogMessage(LogMessageType.CoreResourcesGenericError, exception.Message), exception);
                throw exception;
            }
        }

        /// <summary>
        /// Loads a physical xml file into a logical XmlDocument
        /// </summary>
        /// <param name="path">Physical path of the file</param>
        /// <returns>Logical XmlDocument</returns>
        private XmlDocument LoadResourceFile(string path)
        {

            if (File.Exists(path))
            {

                //open a file stream 
                FileStream fstream= new FileStream(path, FileMode.Open, FileAccess.Read); 


                //initialize a XmlParsercontext and specify the encoding type 
                XmlParserContext myParserContext = new XmlParserContext(null, null, "", 
                XmlSpace.Default, System.Text.Encoding.UTF8); 


                //init XmlTextReader 
                XmlTextReader xtr = new XmlTextReader(fstream, XmlNodeType.Document, myParserContext ); 


                XmlDocument xdoc = new XmlDocument();

                xdoc.Load(xtr);
                xtr.Close();

                return xdoc;
            }
            else
            {
                throw new ApplicationException(path);
            }
        }

        /// <summary>
        /// Retrieves the translation of a given key from a resource file
        /// </summary>
        /// <param name="id">Key to look for</param>
        /// <returns>Retrieved translation</returns>
        public string LoadResource(string id)
        {
            string translatedResource;

            try
            {               
                if (this.resourceFile.DocumentElement.SelectSingleNode(string.Format(Constants.XPathTranslationNode, id))!=null)
                    translatedResource = this.resourceFile.DocumentElement.SelectSingleNode(string.Format(Constants.XPathTranslationNode, id)).InnerText;
                 else
                {
                    if (this.resourceFile.DocumentElement.SelectSingleNode(string.Format(Constants.XPathTranslationNode, "ERROR_Resource_label"))==null)
                        translatedResource = this.resourceFile.DocumentElement.SelectSingleNode(string.Format(Constants.XPathTranslationNode, "ERROR_Resource_label")).InnerText;
                    else
                        translatedResource = string.Format(Errors.ERROR_Resource_label, id);
                }
            }
            catch
            {
                translatedResource = string.Format(Errors.ERROR_Resource_label, id);
            }

            return translatedResource;
        }
    }
}
